package com.hyz.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyz.reggie.controllerApi.CategoryControllerApi;
import com.hyz.reggie.pojo.Category;
import com.hyz.reggie.pojo.R;
import com.hyz.reggie.service.CategoryService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController implements CategoryControllerApi {
    @Autowired
    private CategoryService service;

@Override
@GetMapping("/page")
    public R findAllCategory(Integer page, Integer pageSize) {
        if (page == null || page.equals("") || pageSize == null || pageSize.equals("") || pageSize <= 0) {
            return R.error("看，是傻逼~");
        }
        LambdaQueryWrapper<Category> qwq = new LambdaQueryWrapper<>();
        qwq.orderByAsc(Category::getSort);
        List<Category> list = service.list(qwq);
        IPage<Category> iPage = new Page<>(page, pageSize);
        iPage = service.page(iPage);
        iPage.setRecords(list);
        return R.success(iPage);
    }

    @Override
    @PostMapping
    public R addCategory(@RequestBody Category category) {
        if (category == null) {
            return R.error("做个人吧你~");
        }
        String name = category.getName();
        LambdaQueryWrapper<Category> qwq = new LambdaQueryWrapper<>();
        qwq.eq(Category::getName, name);
        Category one = service.getOne(qwq);
        if (one != null) {
            return R.error("菜系已存在，请勿重复添加~");
        }
        service.save(category);
        return R.success("添加成功~");
    }


    @PutMapping
    public R modifyCategory(@RequestBody Category category) {
        if (category == null) {
            return R.error("做个人吧你~");
        }
        boolean flag = service.updateById(category);
        return flag ? R.success("修改成功~") : R.error("没有这个菜系~");
    }

    @DeleteMapping
    public R removeCg(Long id) {
        if (id == null) {
            return R.error("做个人吧你~");
        }
        service.delete(id);
        return R.success("删除成功~");
    }

    @GetMapping("/list")
    public R list(Integer type) {
        LambdaQueryWrapper<Category> qwq = new LambdaQueryWrapper<>();
        if (type != null) {
            qwq.eq(Category::getType, type);
        }
        List<Category> list = service.list(qwq);
        return R.success(list);
    }


}

